package com.yoke.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yoke.system.log.SystemLog;
import com.yoke.util.JsonUtil;
import com.yoke.util.StringUtil;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;

/**
 * Created by jiangzeyin on 2017/9/22.
 */
@Service
public class VisitorsService extends BaseService {

    public File getUserVisitorsFile(String userName) {
        File file = new File(getCustomerFile(), userName);
        return new File(file, "visitors.conf");
    }

    public JSONObject getInfoById(String userName, String id) {
        if (StringUtil.IsEmpty(id))
            return null;
        JSONArray jsonArray;
        try {
            jsonArray = getUserVisitorsJson(userName);
        } catch (IOException e) {
            SystemLog.ERROR().error("异常", e);
            return null;
        }
        if (jsonArray == null)
            return null;
        JSONObject jsonObject = null;
        for (Object item : jsonArray) {
            JSONObject temp = (JSONObject) item;
            String id_ = temp.getString("id");
            if (id.equals(id_)) {
                jsonObject = temp;
                break;
            }
        }
        return jsonObject;
    }

    public boolean checkUserName(String userName, String cName) {
        JSONArray jsonArray;
        try {
            jsonArray = getUserVisitorsJson(userName);
        } catch (IOException e) {
            SystemLog.ERROR().error("异常", e);
            return false;
        }
        if (jsonArray == null)
            return true;
        boolean flag = true;
        for (Object item : jsonArray) {
            JSONObject jsonObject = (JSONObject) item;
            String name = jsonObject.getString("name");
            if (cName.equals(name)) {
                flag = false;
                break;
            }
        }
        return flag;
    }

    public JSONArray getUserVisitorsJson(String userName) throws IOException {
        File user = getUserVisitorsFile(userName);
        if (!user.exists())
            return null;
        return (JSONArray) JsonUtil.readJson(user.getPath());
    }

    public void saveUserVisitorsJson(String userName, JSONArray jsonArray) throws IOException {
        File user = getUserVisitorsFile(userName);
        JsonUtil.saveJson(user.getPath(), jsonArray);
    }
}
